package raceReservationServer.loginGateway;

import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;

import authorizationRMI.*;

public class AuthRMIGateway implements IAuthorizeGateway {
	/**
	 * Add your code to invoke the Authorization RMI Server here Remember you
	 * must use the interface and exceptions contained in
	 * AuthorizationRMIClient.jar THIS SECTION BELONGS TO THE FIRST ASSIGNMENT
	 */
	private static IAuthorizationRMI iAuth;
		
	
	
	public AuthRMIGateway(String serviceUri) {
		String[] params = serviceUri.split(" ");
		String uri="//"+params[0]+":"+params[1]+"/"+params[2];	
		getAuthManager(uri);
	}

	public RunnerDO login(String user, String pass) throws InvalidUserException, InvalidPasswordException {
		//Posiblemente habrá que añadir más exceptions en el throws
		Runner runner = null;
		
		try {
			runner = iAuth.login(user, pass);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidUserException e){
			System.out.println("Invalid user");
			throw e;
		} catch (InvalidPasswordException e) {
			System.out.println("Invalid password");
			throw e;
		}
		RunnerDO runnerDO= new RunnerDO(runner.Username(), runner.getPassword(), runner.getName(), runner.getAge(), runner.getSex());
		return runnerDO;
	}
	
	private void getAuthManager(String serviceUri) {
		if (System.getSecurityManager() == null) {
			System.setSecurityManager(new RMISecurityManager());
		}
		try {
			iAuth = (IAuthorizationRMI) Naming.lookup(serviceUri);

		} catch (Exception e) {
			System.err.println("Error in Authorization Manager.  getAuthManager(): " + e.getMessage());
		}
	}
}
